import {Page} from '@/base/Page';
import {deleteRole, getRoleList} from '@/base/api/RoleApi';
import {Role} from '@/base/model/Role';

class Form {
  name = '';
  companyId = [];
}

export class ListBloc {
  form = new Form();

  paged: Page<Role> = new Page<Role>([], 0, 1, 15, 0, []);
  loading = false;
  isShowAddModal = false;
  isShowRoleModal = false;
  isShowAccountNumModal = false;

  load(pageIndex: number, pageSize: number) {
    this.loading = true;
    return getRoleList({
      pageIndex,
      pageSize,
      name: this.form.name,
      companyId: this.form.companyId
    }).then((res) => {
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });
  }

  removeItem(dateItem: Role) {
    this.loading = true;
    return deleteRole(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  reset() {
    this.form = new Form();
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }

  changeAddModal() {
    this.isShowAddModal = !this.isShowAddModal;
    this.reset();
  }

  changeRoleModal() {
    this.isShowRoleModal = !this.isShowRoleModal;
    if (!this.isShowRoleModal) {
      this.load(this.paged.pageIndex, this.paged.pageSize);
    }
  }

  changeAccountNumModal() {
    this.isShowAccountNumModal = !this.isShowAccountNumModal;
  }

  getAccountNum(id: number) {
    const item = this.paged.extras.find(x => x.id === id);
    return item == null ? '' : item.num;
  }
}
